<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品ID" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="请输入商品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商家名称" prop="merchantName">
        <el-input
          v-model="queryParams.merchantName"
          placeholder="请输入商家名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商家邮箱" prop="merchantEmail">
        <el-input
          v-model="queryParams.merchantEmail"
          placeholder="请输入商家邮箱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['zhongchuangauto:zcproduct:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['zhongchuangauto:zcproduct:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['zhongchuangauto:zcproduct:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-upload"
          size="mini"
          @click="openUploadDialog"
          v-hasPermi="['zhongchuangauto:zcproduct:create']"
        >上传商品信息</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="zcproductList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="productId" />
      <el-table-column label="商品ID" align="center" prop="productCode" />
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="分类" align="center" prop="category" />
      <el-table-column label="规格" align="center" prop="spec" />
      <el-table-column label="商家名称" align="center" prop="merchantName" />
      <el-table-column label="邮箱" align="center" prop="merchantEmail" />
      <el-table-column label="账户名" align="center" prop="accountName" />
      <el-table-column label="开户行" align="center" prop="bankName" />
      <el-table-column label="开户账号" align="center" prop="accountNo" />
      <el-table-column label="强国实付金额" align="center" prop="qgPayAmount" />
      <el-table-column label="强国分佣比例" align="center" prop="qgCommRatio" />
      <el-table-column label="强国结算金额" align="center" prop="qgSettleAmount" />
      <el-table-column label="中创分佣比例" align="center" prop="zcCommRatio" />
      <el-table-column label="中创结算金额" align="center" prop="zcSettleAmount" />
      <el-table-column label="商家分佣比例" align="center" prop="merchantCommRatio" />
      <el-table-column label="商家结算金额" align="center" prop="merchantSettleAmount" />
      <el-table-column label="润砚分佣比例" align="center" prop="runyanCommRatio" />
      <el-table-column label="润砚结算金额" align="center" prop="runyanSettleAmount" />
      <el-table-column label="翰能分佣比例" align="center" prop="hannengCommRatio" />
      <el-table-column label="翰能结算金额" align="center" prop="hannengSettleAmount" />
      <el-table-column label="滨河分佣比例" align="center" prop="binheCommRatio" />
      <el-table-column label="滨河结算金额" align="center" prop="binheSettleAmount" />
      <el-table-column label="运营状态" align="center" prop="status" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['zhongchuangauto:zcproduct:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['zhongchuangauto:zcproduct:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品ID" prop="productCode">
          <el-input v-model="form.productCode" placeholder="请输入商品ID" />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="form.category" placeholder="请输入分类" />
        </el-form-item>
        <el-form-item label="规格" prop="spec">
          <el-input v-model="form.spec" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商家名称" prop="merchantName">
          <el-input v-model="form.merchantName" placeholder="请输入商家名称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="merchantEmail">
          <el-input v-model="form.merchantEmail" placeholder="请输入商家联系邮箱" />
        </el-form-item>
        <el-form-item label="账户名" prop="accountName">
          <el-input v-model="form.accountName" placeholder="请输入账户名" />
        </el-form-item>
        <el-form-item label="开户行" prop="bankName">
          <el-input v-model="form.bankName" placeholder="请输入开户行" />
        </el-form-item>
        <el-form-item label="开户账号" prop="accountNo">
          <el-input v-model="form.accountNo" placeholder="请输入开户账号" />
        </el-form-item>
        <el-form-item label="强国实付金额" prop="qgPayAmount">
          <el-input v-model="form.qgPayAmount" placeholder="请输入强国实付金额" />
        </el-form-item>
        <el-form-item label="强国分佣比例" prop="qgCommRatio">
          <el-input v-model="form.qgCommRatio" placeholder="请输入强国分佣比例 0~1" />
        </el-form-item>
        <el-form-item label="强国结算金额" prop="qgSettleAmount">
          <el-input v-model="form.qgSettleAmount" placeholder="请输入强国结算金额" />
        </el-form-item>
        <el-form-item label="中创分佣比例" prop="zcCommRatio">
          <el-input v-model="form.zcCommRatio" placeholder="请输入中创分佣比例 0~1" />
        </el-form-item>
        <el-form-item label="中创结算金额" prop="zcSettleAmount">
          <el-input v-model="form.zcSettleAmount" placeholder="请输入中创结算金额" />
        </el-form-item>
        <el-form-item label="商家分佣比例" prop="merchantCommRatio">
          <el-input v-model="form.merchantCommRatio" placeholder="请输入商家分佣比例 0~1" />
        </el-form-item>
        <el-form-item label="商家结算金额" prop="merchantSettleAmount">
          <el-input v-model="form.merchantSettleAmount" placeholder="请输入商家结算金额" />
        </el-form-item>
        <el-form-item label="润砚分佣比例" prop="runyanCommRatio">
          <el-input v-model="form.runyanCommRatio" placeholder="请输入润砚分佣比例 0~1" />
        </el-form-item>
        <el-form-item label="润砚结算金额" prop="runyanSettleAmount">
          <el-input v-model="form.runyanSettleAmount" placeholder="请输入润砚结算金额" />
        </el-form-item>
        <el-form-item label="翰能分佣比例" prop="hannengCommRatio">
          <el-input v-model="form.hannengCommRatio" placeholder="请输入翰能分佣比例 0~1" />
        </el-form-item>
        <el-form-item label="翰能结算金额" prop="hannengSettleAmount">
          <el-input v-model="form.hannengSettleAmount" placeholder="请输入翰能结算金额" />
        </el-form-item>
        <el-form-item label="滨河分佣比例" prop="binheCommRatio">
          <el-input v-model="form.binheCommRatio" placeholder="请输入滨河分佣比例 0~1" />
        </el-form-item>
        <el-form-item label="滨河结算金额" prop="binheSettleAmount">
          <el-input v-model="form.binheSettleAmount" placeholder="请输入滨河结算金额" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
<!--        <el-form-item label="创建时间" prop="createdTime">
          <el-date-picker clearable
            v-model="form.createTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updateTime">
          <el-date-picker clearable
            v-model="form.updateTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 上传商品信息对话框 -->
    <el-dialog title="上传商品信息" :visible.sync="dialogVisible" width="60%" @close="handleClose">
      <!-- 上传控件：仅选 1 个，不自动上传 -->
      <el-upload
        ref="upload"
        :action="uploadUrl"
        :headers="uploadHeaders"
        accept=".xlsx,.xls"
        :limit="1"
        :auto-upload="false"
        :on-change="handleChange"
        :before-upload="beforeUpload"
        :on-success="onSuccess"
        :on-error="onError"
        :show-file-list="true"
        drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          只能上传 xlsx / xls，且不超过 5MB
        </div>
      </el-upload>


       预览表格
      <el-table :data="dialogTableData" v-loading="dialogLoading"  size="mini" max-height="400" style="margin-top:15px;">
        <el-table-column label="序号"  type="index" align="center" />
        <el-table-column label="商品ID" align="center" prop="productCode" />
        <el-table-column label="商品名称" align="center" prop="productName" />
        <el-table-column label="分类" align="center" prop="category" />
        <el-table-column label="规格" align="center" prop="spec" />
        <el-table-column label="商家名称" align="center" prop="merchantName" />
        <el-table-column label="商家邮箱" align="center" prop="merchantEmail" />
        <el-table-column label="账户名" align="center" prop="accountName" />
        <el-table-column label="开户行" align="center" prop="bankName" />
        <el-table-column label="开户账号" align="center" prop="accountNo" />
        <el-table-column label="强国实付金额" align="center" prop="qgPayAmount" />
        <el-table-column label="强国分佣比例" align="center" prop="qgCommRatio" />
        <el-table-column label="强国结算金额" align="center" prop="qgSettleAmount" />
        <el-table-column label="中创分佣比例" align="center" prop="zcCommRatio" />
        <el-table-column label="中创结算金额" align="center" prop="zcSettleAmount" />
        <el-table-column label="商家分佣比例" align="center" prop="merchantCommRatio" />
        <el-table-column label="商家结算金额" align="center" prop="merchantSettleAmount" />
        <el-table-column label="润砚分佣比例" align="center" prop="runyanCommRatio" />
        <el-table-column label="润砚结算金额" align="center" prop="runyanSettleAmount" />
        <el-table-column label="翰能分佣比例" align="center" prop="hannengCommRatio" />
        <el-table-column label="翰能结算金额" align="center" prop="hannengSettleAmount" />
        <el-table-column label="滨河分佣比例" align="center" prop="binheCommRatio" />
        <el-table-column label="滨河结算金额" align="center" prop="binheSettleAmount" />
        <el-table-column label="状态" align="center" prop="status" />
        <el-table-column label="备注" align="center" prop="remark" />
      </el-table>
      <div slot="footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" :disabled="dialogTableData.length===0" @click="submitUpload">确 定 导 入</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import { listZcproduct, getZcproduct, delZcproduct, addZcproduct, updateZcproduct,uploadZcproduct } from "@/api/zhongchuangauto/zcproduct";
import { getToken } from '@/utils/auth'
export default {
  name: "Zcproduct",
  data() {
    return {
      inheritAttrs: false,
      dialogVisible:false,
      dialogLoading:false,
      dialogTableData:[],
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      fileUrl:'',
      uploadUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      components: {},
      props: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品信息表格数据
      zcproductList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productCode: null,
        productName: null,
        category: null,
        spec: null,
        merchantName: null,
        merchantEmail: null,
        accountName: null,
        bankName: null,
        accountNo: null,
        qgPayAmount: null,
        qgCommRatio: null,
        qgSettleAmount: null,
        zcCommRatio: null,
        zcSettleAmount: null,
        merchantCommRatio: null,
        merchantSettleAmount: null,
        runyanCommRatio: null,
        runyanSettleAmount: null,
        hannengCommRatio: null,
        hannengSettleAmount: null,
        binheCommRatio: null,
        binheSettleAmount: null,
        status: null,
        createTime: null,
        updateTime: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          productCode: [
            { required: true, message: "商品ID不能为空", trigger: "blur" }
          ],
            productName: [
            { required: true, message: "商品名称不能为空", trigger: "blur" }
          ],
            category: [
            { required: true, message: "分类不能为空", trigger: "blur" }
          ],
            merchantName: [
            { required: true, message: "商家名称不能为空", trigger: "blur" }
          ],
            accountName: [
            { required: true, message: "账户名不能为空", trigger: "blur" }
          ],
            bankName: [
            { required: true, message: "开户行不能为空", trigger: "blur" }
          ],
            accountNo: [
            { required: true, message: "开户账号不能为空", trigger: "blur" }
          ],
            qgPayAmount: [
            { required: true, message: "强国实付金额不能为空", trigger: "blur" }
          ],
            qgCommRatio: [
            { required: true, message: "强国分佣比例 0~1不能为空", trigger: "blur" }
          ],
            zcCommRatio: [
            { required: true, message: "中创分佣比例 0~1不能为空", trigger: "blur" }
          ],
            merchantCommRatio: [
            { required: true, message: "商家分佣比例 0~1不能为空", trigger: "blur" }
          ],
          runyanCommRatio: [
            { required: true, message: "润砚分佣比例 0~1不能为空", trigger: "blur" }
          ],
          runyanSettleAmount: [
            { required: true, message: "润砚结算金额不能为空", trigger: "blur" }
          ],
          hannengCommRatio: [
            { required: true, message: "翰能分佣比例 0~1不能为空", trigger: "blur" }
          ],
          hannengSettleAmount: [
            { required: true, message: "翰能结算金额不能为空", trigger: "blur" }
          ],
          binheCommRatio: [
            { required: true, message: "滨河分佣比例 0~1不能为空", trigger: "blur" }
          ],
          binheSettleAmount: [
            { required: true, message: "滨河结算金额不能为空", trigger: "blur" }
          ],
        }
      };
    },
    computed: {},
    watch: {},
    created() {
      this.getList();
    },
      methods: {
        /* 1. 打开上传商品信息弹窗 */
        openUploadDialog() {
          this.dialogVisible = true
        },
        /* 2. 关闭上传商品信息弹窗 - 清空已上传的列表数据 */
        handleClose() {
          this.dialogTableData = []
          this.dialogVisible=false
          this.rawFile = null
          this.$refs.upload.clearFiles()
        },

        /* 3. 文件选择后解析 解析 excel -> 表格数据（与主页字段一致） */
        handleChange(file) {
          this.rawFile = file.raw
          this.beforeUpload(file.raw)
          const raw = file.raw || file
          if (!raw || !(raw instanceof Blob)) {
            this.$message.error('未获取到有效文件')
            return
          }
          //读取xlsx文件内容，按照标题内容遍历到dialogTableData变量中
          const reader = new FileReader()
          reader.onload = e => {
            const wb = XLSX.read(e.target.result, { type: 'array' })
            const sheet = wb.Sheets[wb.SheetNames[0]]
            const json = XLSX.utils.sheet_to_json(sheet)
            this.dialogTableData = json.map(row => ({
              productCode: row['商品ID'] || '',
              productName: row['商品名称'] || '',
              category: row['分类'] || '',
              spec: row['规格'] || '',
              merchantName: row['商家'] || '',
              merchantEmail:row['邮箱'] || '',
              accountName: row['账户名'] || '',
              bankName:row['开户行'] || '',
              accountNo: row['开户账号'] || '',
              qgPayAmount: row['强国实付金额'] || '',
              qgCommRatio: row['强国分佣比例'] || '',
              qgSettleAmount:row['强国结算金额'] || '',
              zcCommRatio: row['中创分佣比例'] || '',
              zcSettleAmount:row['中创结算金额'] || '',
              merchantCommRatio: row['商家分佣比例'] || '',
              merchantSettleAmount: row['商家结算金额'] || '',
              runyanCommRatio: row['润砚分佣比例'] || '',
              runyanSettleAmount: row['润砚结算金额'] || '',
              hannengCommRatio: row['翰能分佣比例'] || '',
              hannengSettleAmount: row['翰能结算金额'] || '',
              binheCommRatio: row['滨河分佣比例'] || '',
              binheSettleAmount: row['滨河结算金额'] || '',
              status: row['运营状态'] || '',
              remark:row['备注'] || ''
            }))
          }
          reader.readAsArrayBuffer(raw)
        },

        /* 4. 校验文件 */
        beforeUpload(file) {
          const isXlsx = /.(xlsx|xls)$/i.test(file.name)
          const isLt5M = file.size / 1024 / 1024 < 5
          if (!isXlsx) this.$message.error('只能上传 xlsx/xls 文件')
          if (!isLt5M) this.$message.error('大小不能超过 5MB')
          return isXlsx && isLt5M
        },

        /* 5.触发上传提交文件动作*/
        submitUpload() {
          // 校验：有没有选文件
          const files = this.$refs.upload.uploadFiles;
          if (!files || files.length === 0) {
            this.$message.warning('请先选择文件');
            return;
          }
          // 手动提交
          this.$refs.upload.submit();
        },
        // 6.上传文件处理
        onSuccess(res){
          this.fileUrl = res.url;// 拿到上传文件的url
          this.$message.success('上传成功，开始解析……');
          // 立即调用后端解析接口
          uploadZcproduct({ fileUrl: res.url }).then( r =>{
              this.$message.success(r.msg);
              this.handleClose()
              this.getList()
            }
          );
        },
        onError(err){
          this.$message.error('上传失败：' + err.message)
        },
        /** 查询商品信息列表 */
        getList() {
          this.loading = true;
          listZcproduct(this.queryParams).then(response => {
            this.zcproductList = response.rows;
            this.total = response.total;
            this.loading = false;
          });
        },
        // 取消按钮
        cancel() {
          this.open = false;
          this.reset();
        },
        // 表单重置
        reset() {
          this.form = {
            productId: null,
            productCode: null,
            productName: null,
            category: null,
            spec: null,
            merchantName: null,
            merchantEmail: null,
            accountName: null,
            bankName: null,
            accountNo: null,
            qgPayAmount: null,
            qgCommRatio: null,
            qgSettleAmount: null,
            zcCommRatio: null,
            zcSettleAmount: null,
            merchantCommRatio: null,
            merchantSettleAmount: null,
            runyanCommRatio: null,
            runyanSettleAmount: null,
            hannengCommRatio: null,
            hannengSettleAmount: null,
            binheCommRatio: null,
            binheSettleAmount: null,
            status: null,
            remark: null,
            createTime: null,
            updateTime: null
          };
          this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
          this.queryParams.pageNum = 1;
          this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
          this.resetForm("queryForm");
          this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
          this.ids = selection.map(item => item.productId)
          this.single = selection.length!==1
          this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
          this.reset();
          this.open = true;
          this.title = "添加商品信息";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
          this.reset();
          const productId = row.productId || this.ids
          getZcproduct(productId).then(response => {
            this.form = response.data;
            this.open = true;
            this.title = "修改商品信息";
          });
        },
        /** 提交按钮 */
        submitForm() {
          this.$refs["form"].validate(valid => {
            if (valid) {
              if (this.form.productId != null) {
                updateZcproduct(this.form).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              } else {
                addZcproduct(this.form).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
              }
            }
          });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
          const productIds = row.productId || this.ids;
          this.$modal.confirm('是否确认删除商品信息编号为"' + productIds + '"的数据项？').then(function() {
            return delZcproduct(productIds);
          }).then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          }).catch(() => {});
        },
        /** 导出按钮操作 */
        handleExport() {
          this.download('zhongchuangauto/zcproduct/export', {
            ...this.queryParams
          }, `zcproduct_${new Date().getTime()}.xlsx`)
        }
      }
    };
</script>
